package cn.akwangl.socket.simple;

import lombok.extern.slf4j.Slf4j;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Socket 简单实现测试.Server 端实现.
 * <p>
 * 在这个用例中,当客户端输入什么,服务端就返回什么.
 * 如果客户端输入{@link SimpleService#QUIT}关键字则关闭Socket连接.
 *
 * @author 阿坤同学
 * @date 2022/6/18 15:05
 * @since 0.0.6
 */
@Slf4j
public class SimpleService {
    public static final int SERVER_PORT = 7000;

    public static final String QUIT = "quit";

    public static final String SERVER_ADDRESS = "localhost";

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
            log.info("server 启动成功,服务端口:{},正在等待客户端连接...", SERVER_PORT);
            while (true) {
                Socket socket = serverSocket.accept();
                String clientHostAddress = socket.getInetAddress().getHostAddress();
                log.info("接受来自客户端:{}地址的连接,开始会话...", clientHostAddress);

                DataInputStream in = new DataInputStream(socket.getInputStream());
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                String clientMsg;
                while ((clientMsg = in.readUTF()) != null) {
                    log.info("服务端:收到来自客户端消息:{}", clientMsg);
                    // 如果客户端消息为退出命令则断开socket连接,否则将消息写回客户端
                    if (QUIT.equals(clientMsg)) {
                        socket.close();
                        log.info("client {} socket 已断开连接,欢迎下次使用.", clientHostAddress);
                        break;
                    } else {
                        out.writeUTF(clientMsg);
                    }
                }
            }
        } catch (IOException e) {
            log.error("socket 通信异常", e);
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    log.error("socket 连接关闭失败", e);
                }
            }
        }
    }
}
